import React, { useEffect, useState } from "react";
import FormItem from "./FormItem";
import AdvancedFormItem from "./AdvancedFormItem";
import { Form, Collapse, Input } from "antd";
import "./index.scss";

const { Panel } = Collapse;
const XmlRootForm = (props) => {
  const [form] = Form.useForm();
  const [baseInputsList, setBaseInputsList] = useState([]);
  const [advanceSetupsList, setAdvanceSetupsList] = useState([]);

  useEffect(() => {
    if (
      props &&
      props.schema &&
      props.schema.base &&
      props.schema.base.craft.inputs
    ) {
      setBaseInputsList(props.schema.base.craft.inputs);
    }
    if (
      props &&
      props.schema &&
      props.schema.advance &&
      props.schema.advance.setups
    ) {
      setAdvanceSetupsList(props.schema.advance.setups);
    }
  }, []);

  const compair = (rule, value, callback) => {
    let reg = /^[^ ]+$/;
    if (reg.test(value)) {
      callback();
      return Promise.resolve();
    } else {
      return Promise.reject("字母数字下划线不能有空格");
    }
  };

  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 19 },
  };

  return (
    <div className="container">
      {baseInputsList?.length ? (
        <Form form={form}>
          <Collapse defaultActiveKey={["1", "2"]}>
            <Panel header="基础设置" key="1" style={{ background: "#F4F4F4" }}>
              <Form.Item
                {...formItemLayout}
                label="项目名称："
                name="projectName"
                rules={[
                  { required: true, message: "必填项", validator: compair },
                ]}
              >
                <Input />
              </Form.Item>

              {baseInputsList?.length &&
                baseInputsList.map((inputData, index) => {
                  return (
                    <FormItem
                      key={index}
                      type="basic"
                      fieldData={inputData}
                      itemKey={inputData.key}
                      form={form}
                    ></FormItem>
                  );
                })}
            </Panel>
            {advanceSetupsList?.length ? (
              <Panel
                header="高级设置"
                key="2"
                style={{ background: "#F4F4F4" }}
              >
                {advanceSetupsList?.length &&
                  advanceSetupsList.map((setup, index) => {
                    return (
                      <AdvancedFormItem
                        key={index}
                        advancedSetupItem={setup}
                        form={form}
                      ></AdvancedFormItem>
                    );
                  })}
              </Panel>
            ) : (
              ""
            )}
          </Collapse>
        </Form>
      ) : (
        ""
      )}
    </div>
  );
};

export default XmlRootForm;
